package com.orange.core.aop;

import com.orange.core.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Pointcut("execution(public * com.orange..controller..*.*(..))")
    public void point() {
    }

    @Around("point()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Throwable throwable = null;
        try {
            HttpServletRequest request = RequestUtil.getRequest();
            if (request != null) {
                log.info("Request Url: {}", request.getRequestURL().toString());
                log.info("Request Method: {}", request.getMethod());
                log.info("Request Class Method: {}.{}", proceedingJoinPoint.getSignature().getDeclaringTypeName(), proceedingJoinPoint.getSignature().getName());
                log.info("Request Args: {}", proceedingJoinPoint.getArgs());
            }
            return proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            throwable = e;
            throw e;
        } finally {
            if (throwable != null) {
                log.info("Response Fail Reason: {}", throwable.getMessage());
            } else {
                log.info("Response success");
            }
            log.info("Response Time: {} ms", System.currentTimeMillis() - startTime);
        }
    }
}
